package com.msconfig.mvp.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.geo.msconfig.R;
import com.msconfig.bean.deviceInfoBean.TagDeviceInfo;
import com.msconfig.device.CommandParseManage;
import com.msconfig.device.CommandSendManage;
import com.msconfig.device.DeviceManage;
import com.msconfig.device.GetSendCommandList;
import com.msconfig.device.TagSendCommand;
import com.msconfig.event.DeviceUpdateEvent;
import com.msconfig.event.WifiFrequencyBandDialogDismissEvent;
import com.msconfig.event.WifiModelDialogDismissEvent;
import com.msconfig.io.ConnectListener;
import com.msconfig.mvp.view.activity.SetupWifiFrequencyBandDialogActivity;
import com.msconfig.mvp.view.activity.SetupWifiModelDialogActivity;
import com.msconfig.mvp.view.activity.base.BaseMvpFragment;
import com.msconfig.mvp.view.activity.base.BasePresenter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import static android.view.View.VISIBLE;

public class SetupWifiFragment extends BaseMvpFragment implements View.OnClickListener {
    private FrameLayout flLoading;
    private ImageView ivLoading;
    private Animation setupAnim;
    private ImageView ivCommonBack;
    private TextView tvCommonTitle;
    private TextView tvWifiModel;
    private TextView tvWifiFrequencyBand;
    private RelativeLayout rlWifiFrequencyBand;
    private RelativeLayout rlWifiModel;
    private Button btnDetermine;
    private View includeWifiModelFirst;
    private View includeWifiModelSecond;
    private View includeWifiModelThird;
    private RelativeLayout rlSsid;
    private EditText etSsid;
    private RelativeLayout rlPassword;
    private EditText etPassword;
    private RelativeLayout rlAutoGetIp;
    private ImageView ivSwitchGetIpOn;
    private ImageView ivSwitchGetIpOff;
    private RelativeLayout rlIpMessage;
    private RelativeLayout rlIpAdress;
    private EditText etIpAdress;
    private RelativeLayout rlSubnetLength;
    private EditText etSubnetLength;
    private RelativeLayout rlDefaultGateway;
    private EditText etDefaultGateway;
    private RelativeLayout rlDns1;
    private EditText etDns1;
    private RelativeLayout rlDns2;
    private EditText etDns2;
    private RelativeLayout rlNetworkingMessage;
    private RelativeLayout rlPrefix;
    private EditText etPrefix;
    private RelativeLayout rlApPassword;
    private EditText etApPassword;
    private ImageView ivOpenWifi;
    private ImageView ivCloseWifi;
    private ConstraintLayout clWifiLayout;
    private TagDeviceInfo deviceInfo;
    private Context context;
    private boolean isSetupDefail;
    private MyHandler myHandler;
    protected static final int MSG_SET_UP_DEFAIL =1;//设置失败
    public static final String WIFIMODELNAME ="modelName";
    public static final String WIFIBAND ="wifiBand";
    private String modelName;


    //负责更新UI
    private static class MyHandler extends Handler {
        WeakReference<SetupWifiFragment> weakReference;
        private MyHandler(SetupWifiFragment fragment) {
            weakReference = new WeakReference<SetupWifiFragment>(fragment);
        }
        @Override
        public void handleMessage(Message msg) {
            SetupWifiFragment fragment = weakReference.get();
            if (fragment != null) {
                switch (msg.what) {
                    case MSG_SET_UP_DEFAIL:
                        if(fragment.flLoading.getVisibility()==VISIBLE){//动画还在，说明设置事件过久设置失败
                            fragment.stopAnim();
                            fragment.isSetupDefail=true;
                            fragment.showToast(R.string.toast_setup_defail);
                        }
                        break;
                }
            }
        }
    }


    public static SetupWifiFragment newInstance() {
        Bundle args = new Bundle();
        SetupWifiFragment fragment = new SetupWifiFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //GETALL成功   进来先读取主机数据显示出来
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void showAnalysisGNSSDataSuccess(DeviceUpdateEvent.UpdateDialogGetRtkSuccessStatus event){
        if(ConnectListener.CommanderStatus.SUCCESS != DeviceManage.getInstance().getConnectedStatus())
            return;
        switch (deviceInfo.wifiInfo.mWifiModel){
            case "MASTER":
                modelName=getResources().getString(R.string.hotspot);
                onClickWifiModelHotspot();
                break;
            case "CLIENT":
                modelName=getResources().getString(R.string.wifi_hotspot);
                onClickWifiModelWifiHotspot();
                break;
            case "WDS_WIFI":
                modelName=getResources().getString(R.string.central_node_wifi);
                onClickWifiModelCentralNodeWifi();
                break;
            case "WDS_4G":
                modelName=getResources().getString(R.string.central_node_4G);
                onClickWifiModelCentralNode4g();
                etPrefix.setText(deviceInfo.wifiInfo.mPrefix);
                etApPassword.setText(deviceInfo.wifiInfo.mApPass);
                break;
            case "WDS":
                modelName=getResources().getString(R.string.child_node);
                onClickWifiModelChildNode();
                etPrefix.setText(deviceInfo.wifiInfo.mPrefix);
                etApPassword.setText(deviceInfo.wifiInfo.mApPass);
                break;
        }
        tvWifiModel.setText(modelName);
        etSsid.setText(deviceInfo.wifiInfo.mSsid);
        etPassword.setText(deviceInfo.wifiInfo.mPassword);
        if(deviceInfo.wifiInfo.mDHCP){
            onClickTurnOff();
        }else{
            onClickTurnOn();
        }
        etIpAdress.setText(deviceInfo.wifiInfo.mIpAdress);
        etSubnetLength.setText(deviceInfo.wifiInfo.mSubnetLength);
        etDefaultGateway.setText(deviceInfo.wifiInfo.mDefaultGateway);
        etDns1.setText(deviceInfo.wifiInfo.mDns1);
        etDns2.setText(deviceInfo.wifiInfo.mDns2);
        tvWifiFrequencyBand.setText(deviceInfo.wifiInfo.mWifiBand);
    }

    //开始动画
    public void startAnim(){
        setupAnim = AnimationUtils.loadAnimation(context, R.anim.anim_round_rotate);
        LinearInterpolator interpolator = new LinearInterpolator();  //设置匀速旋转，在xml文件中设置会出现卡顿
        setupAnim.setInterpolator(interpolator);
        if (setupAnim != null) {
            btnDetermine.setEnabled(false);
            flLoading.setVisibility(VISIBLE);
            ivLoading.startAnimation(setupAnim);  //开始动画
        }
    }

    //停止动画
    private void stopAnim() {
        if (setupAnim != null) {
            btnDetermine.setEnabled(true);
            setupAnim=null;
            flLoading.setVisibility(View.GONE);
            ivLoading.clearAnimation();
        }
    }

    //3.点击确定按钮准备设置数据
    private void onClickBtnDetermine() {
        isSetupDefail=false;
        if(ConnectListener.CommanderStatus.SUCCESS != DeviceManage.getInstance().getConnectedStatus()){
            Toast.makeText(context, R.string.toast_isdisconnect, Toast.LENGTH_SHORT).show();
            return;
        }
        String mode = "";
        String wifiModel = tvWifiModel.getText().toString().trim();
        if(wifiModel.equals(getResources().getString(R.string.hotspot))){
            mode="MASTER";
        }else if(wifiModel.equals(getResources().getString(R.string.wifi_hotspot))){
            mode="CLIENT";
        }else if(wifiModel.equals(getResources().getString(R.string.central_node_wifi))){
            mode="WDS_WIFI";
        }else if(wifiModel.equals(getResources().getString(R.string.central_node_4G))){
            mode="WDS_4G";
        }else if(wifiModel.equals(getResources().getString(R.string.child_node))){
            mode="WDS";
        }
        String ssid = etSsid.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        int dhcp;
        if(ivSwitchGetIpOn.getVisibility()== View.VISIBLE){
            dhcp =1;
        }else{
            dhcp =0;
        }
        String ipAdress = etIpAdress.getText().toString().trim();
        String subnetLength = etSubnetLength.getText().toString().trim();
        String defaultGateway = etDefaultGateway.getText().toString().trim();
        String dns1 = etDns1.getText().toString().trim();
        String dns2 = etDns2.getText().toString().trim();
        int band5g;
        if(tvWifiFrequencyBand.getText().toString().trim().equals(getString(R.string.band_5g))){
            band5g =1;
        }else{
            band5g =0;
        }
        String prefix = etPrefix.getText().toString().trim();
        String apName = etApPassword.getText().toString().trim();
        //开始设置动画
        startAnim();
        ArrayList<TagSendCommand> sendCommandList = GetSendCommandList.getWifiCommandList(mode, ssid, password, dhcp, ipAdress, subnetLength, defaultGateway, dns1, dns2, band5g, prefix, apName);
        //设置发送命令的集合
        CommandSendManage.getInstance().setSendCommandList(sendCommandList);
        //开始发送命令
        CommandSendManage.getInstance().startSendCommand();

        //3s后判断有没有数据返回，没有代表设置失败
        myHandler = new MyHandler(this);
        myHandler.sendEmptyMessageDelayed(MSG_SET_UP_DEFAIL,8000);

    }

    //设置全部命令成功
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setupAllCommandSucc(DeviceUpdateEvent.DeviceCommandSendStatus event) {
        if(isSetupDefail)//3s内没有得到消息显示设置失败，防止数据延迟之后回来设置成功
            return;

        if(event.getStatus()==2){//超时，发送失败
            stopAnim();
            Toast.makeText(context,event.getFunction()+"设置失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if(event.getStatus()==3){
            //有反馈信息回来
            stopAnim();
            Toast.makeText(context,R.string.toast_setup_success, Toast.LENGTH_SHORT).show();
            backTo();

            //最后再发送一次GETALL获取最新数据
            //得到发送命令的集合
            ArrayList<TagSendCommand> sendCommandList= GetSendCommandList.getGetAllCommandList();
            //设置发送命令额集合
            CommandSendManage.getInstance().setSendCommandList(sendCommandList);
            //开始发送命令
            CommandSendManage.getInstance().startSendCommand();
        }
    }


    @Override
    protected int getLayoutId() {
        return R.layout.layout_fragment_setup_wifi;
    }

    @Override
    protected void initView(View view) {
        ivCommonBack=view.findViewById(R.id.iv_common_back);
        tvCommonTitle=view.findViewById(R.id.tv_common_title);
        tvWifiModel=view.findViewById(R.id.tv_wifi_model);
        tvWifiFrequencyBand=view.findViewById(R.id.tv_wifi_frequency_band);
        rlWifiModel=view.findViewById(R.id.rl_wifi_model);
        rlWifiFrequencyBand=view.findViewById(R.id.rl_wifi_frequency_band);
        btnDetermine=view.findViewById(R.id.btn_determine);
        flLoading=view.findViewById(R.id.fl_loading);
        ivLoading = view.findViewById(R.id.iv_loading);

        includeWifiModelFirst =view.findViewById(R.id.include_wifi_model_first);
        includeWifiModelSecond =view.findViewById(R.id.include_wifi_model_second);
        includeWifiModelThird =view.findViewById(R.id.include_wifi_model_third);


        rlSsid = (RelativeLayout)view.findViewById( R.id.rl_ssid );
        etSsid = (EditText)view.findViewById( R.id.et_ssid );
        rlPassword = (RelativeLayout)view.findViewById( R.id.rl_password );
        etPassword = (EditText)view.findViewById( R.id.et_password );
        rlAutoGetIp = (RelativeLayout)view.findViewById( R.id.rl_auto_get_ip );
        ivSwitchGetIpOn = (ImageView)view.findViewById( R.id.iv_switch_get_ip_on );
        ivSwitchGetIpOff = (ImageView)view.findViewById( R.id.iv_switch_get_ip_off );
        rlIpMessage = (RelativeLayout)view.findViewById( R.id.rl_ip_message );
        rlIpAdress = (RelativeLayout)view.findViewById( R.id.rl_ip_adress );
        etIpAdress = (EditText)view.findViewById( R.id.et_ip_adress );
        rlSubnetLength = (RelativeLayout)view.findViewById( R.id.rl_subnet_length );
        etSubnetLength = (EditText)view.findViewById( R.id.et_subnet_length );
        rlDefaultGateway = (RelativeLayout)view.findViewById( R.id.rl_default_gateway );
        etDefaultGateway = (EditText)view.findViewById( R.id.et_default_gateway );
        rlDns1 = (RelativeLayout)view.findViewById( R.id.rl_dns1 );
        etDns1 = (EditText)view.findViewById( R.id.et_dns1 );
        rlDns2 = (RelativeLayout)view.findViewById( R.id.rl_dns2 );
        etDns2 = (EditText)view.findViewById( R.id.et_dns2 );
        rlNetworkingMessage = (RelativeLayout)view.findViewById( R.id.rl_networking_message );
        rlPrefix = (RelativeLayout)view.findViewById( R.id.rl_prefix );
        etPrefix = (EditText)view.findViewById( R.id.et_prefix );
        rlApPassword = (RelativeLayout)view.findViewById( R.id.rl_ap_password );
        etApPassword = (EditText)view.findViewById( R.id.et_ap_password );
        rlIpMessage = (RelativeLayout) view.findViewById( R.id.rl_ip_message );
        ivOpenWifi = (ImageView) view.findViewById( R.id.iv_switch_wifi_on );
        ivCloseWifi = (ImageView) view.findViewById( R.id.iv_switch_wifi_off );
        clWifiLayout = (ConstraintLayout) view.findViewById( R.id.cl_wifi );

    }

    @Override
    protected void initListener(View view) {
        ivCommonBack.setOnClickListener(this);
        rlWifiModel.setOnClickListener(this);
        rlWifiFrequencyBand.setOnClickListener(this);
        btnDetermine.setOnClickListener(this);
        ivSwitchGetIpOn.setOnClickListener(this);
        ivSwitchGetIpOff.setOnClickListener(this);
        ivOpenWifi.setOnClickListener(this);
        ivCloseWifi.setOnClickListener(this);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showSelectWifiModel(WifiModelDialogDismissEvent event) {
        String wifiModelName = event.getName();
        tvWifiModel.setText(wifiModelName);
        if(wifiModelName.equals(getResources().getString(R.string.hotspot))){
            onClickWifiModelHotspot();

        }else if(wifiModelName.equals(getResources().getString(R.string.wifi_hotspot))){
            onClickWifiModelWifiHotspot();

        }else if(wifiModelName.equals(getResources().getString(R.string.central_node_wifi))){
            onClickWifiModelCentralNodeWifi();

        }else if(wifiModelName.equals(getResources().getString(R.string.central_node_4G))){
            onClickWifiModelCentralNode4g();

        }else if(wifiModelName.equals(getResources().getString(R.string.child_node))){
            onClickWifiModelChildNode();
        }
    }

    private void onClickWifiModelChildNode() {
        includeWifiModelSecond.setVisibility(View.GONE);
        includeWifiModelThird.setVisibility(View.VISIBLE);
    }

    private void onClickWifiModelCentralNode4g() {
        includeWifiModelSecond.setVisibility(View.GONE);
        includeWifiModelThird.setVisibility(View.VISIBLE);
    }

    private void onClickWifiModelCentralNodeWifi() {
        includeWifiModelThird.setVisibility(View.GONE);
        includeWifiModelSecond.setVisibility(View.VISIBLE);
    }

    private void onClickWifiModelWifiHotspot() {
        includeWifiModelThird.setVisibility(View.GONE);
        includeWifiModelSecond.setVisibility(View.VISIBLE);
    }

    private void onClickWifiModelHotspot() {
        includeWifiModelSecond.setVisibility(View.GONE);
        includeWifiModelThird.setVisibility(View.GONE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showSelectWifiFrequencyBand(WifiFrequencyBandDialogDismissEvent event) {
        String model=event.getName();
        tvWifiFrequencyBand.setText(model);
    }


    @Override
    protected void initData() {
        tvCommonTitle.setText("WIFI设置");
        deviceInfo= CommandParseManage.getInstance().getDeviceInfo();
    }

    @Override
    public void onClick(View v) {
        if(v==ivCommonBack){
            backTo();
        }else if(v==rlWifiModel){
            Intent intent=new Intent(getActivity(),SetupWifiModelDialogActivity.class);
            intent.putExtra(WIFIMODELNAME,tvWifiModel.getText().toString().trim());
            startActivity(intent);
        }else if(v==rlWifiFrequencyBand){
            Intent intent=new Intent(getActivity(),SetupWifiFrequencyBandDialogActivity.class);
            intent.putExtra(WIFIBAND,tvWifiFrequencyBand.getText().toString().trim());
            startActivity(intent);
        }else if(v==btnDetermine){
            onClickBtnDetermine();
        }else if(v==ivSwitchGetIpOn){
            onClickTurnOn();
        }else if(v==ivSwitchGetIpOff){
            onClickTurnOff();
        }else if(v==ivCloseWifi){
            onClickWifiOff();
        }else if(v==ivOpenWifi){//关闭wifi,
            onClickWifiOn();
        }
    }

    private void onClickWifiOff() {
        ivCloseWifi.setVisibility(View.GONE);
        ivOpenWifi.setVisibility(View.VISIBLE);
        clWifiLayout.setVisibility(View.VISIBLE);
//        String strCommand="SET,DEVICE.WIFI.EXT_ANTENNA,1\r\n";
//        DeviceManage.getInstance().sendCommand(strCommand);
    }

    private void onClickWifiOn() {
        ivOpenWifi.setVisibility(View.GONE);
        ivCloseWifi.setVisibility(View.VISIBLE);
        clWifiLayout.setVisibility(View.GONE);
//        String strCommand="SET,DEVICE.WIFI.EXT_ANTENNA,0\r\n";
//        DeviceManage.getInstance().sendCommand(strCommand);
    }

    //当Activity与fragment建立关联时调用
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }

    @Override
    public void onDestroy() {
        if(myHandler!=null){
            myHandler.removeCallbacksAndMessages(null);
            myHandler=null;
        }
        stopAnim();
        super.onDestroy();
    }

    private void onClickTurnOff() {
        ivSwitchGetIpOff.setVisibility(View.GONE);
        ivSwitchGetIpOn.setVisibility(View.VISIBLE);
        rlIpMessage.setVisibility(View.GONE);
    }

    private void onClickTurnOn() {
        ivSwitchGetIpOn.setVisibility(View.GONE);
        ivSwitchGetIpOff.setVisibility(View.VISIBLE);
        rlIpMessage.setVisibility(View.VISIBLE);
    }

    @Override
    protected void createPresenter(List<BasePresenter> mPresenters) {

    }
}
